package com.czy.owner.ui.store;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.text.Html;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.overlay.DrivingRouteOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.czy.owner.R;
import com.czy.owner.api.BindStoreApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.NearStoreListModel;
import com.czy.owner.entity.OwnerInfoModel;
import com.czy.owner.entity.StoreDataModel;
import com.czy.owner.entity.StoreDetailInfoModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.MyLoadView;
import com.czy.owner.permission.Acp;
import com.czy.owner.permission.AcpListener;
import com.czy.owner.permission.AcpOptions;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.AMapUtil;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.glide.GlideUtils;
import com.czy.owner.widget.ImageCycleView;
import com.czy.owner.widget.MyScrollView;
import com.czy.owner.widget.UniversalDialog;
import com.easemob.cases.MessageHelper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by wangyang on 2016/6/24 0024.
 */
public class NoBindStoreDetailActivity extends BaseActivity implements /*AMapNaviListener*/RouteSearch.OnRouteSearchListener, MyScrollView.ScrollViewLine {
    @BindView(R.id.myscrollview)
    MyScrollView myScrollView;
    @BindView(R.id.line_headview)
    LinearLayout lineHeadView;
    @BindView(R.id.img_store_view)
    ImageCycleView imgTop;
    @BindView(R.id.tv_store_number)
    TextView tvStoreNumber;
    @BindView(R.id.tv_store_adress)
    TextView tvStoreAdress;
    @BindView(R.id.tv_title_company_name)
    TextView tvTitleCompanyName;
    @BindView(R.id.tv_store_describe)
    TextView tvStoreDescribe;
    @BindView(R.id.floatinImgBtn)
    FloatingActionButton floatingActionBtn;
    @BindView(R.id.mapview)
    MapView mapView;
    private AMap amap;
    //    private AMapNavi aMapNavi;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    //标识，用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFirstLoc = true;
    private RouteSearch mRouteSearch;
    private LatLonPoint mStartPoint;//起点，
    private LatLonPoint mEndPoint;//终点，
    private int storeId = 0;
    private MyLoadView myLoadView;
    private String storeName;
    private String stroeLogo;
    private String description;
    private String serviceNumber;
    private String storeLocation;
    private double gprsX;
    private double gprsY;
    private ArrayList<String> mImageUrl = null;
    private OwnerInfoModel ownerInfoModel = null;
    private ArrayList<String> mImageUrlweb = new ArrayList<>();//banner的点击
   private boolean isScan = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapView.onCreate(savedInstanceState);// 此方法必须重写

    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_no_bind_store_detail;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        init();
        initLoc();
    }

    @Override
    protected void updateViews() {

    }

    private void init() {
        if ((Build.VERSION.SDK_INT >= 23)) {
            onClickLocation();
        }
        isScan = getIntent().getBooleanExtra("isScan",false);
        ownerInfoModel = UserHelper.getInstance().getOwnerInfoModel(NoBindStoreDetailActivity.this);
        storeName = getIntent().getStringExtra("storeName");
        stroeLogo = getIntent().getStringExtra("stroeLogo");
        description = getIntent().getStringExtra("description");
        serviceNumber = getIntent().getStringExtra("serviceNumber");
        storeLocation = getIntent().getStringExtra("storeLocation");
        gprsX = getIntent().getDoubleExtra("gprsX", 0);
        gprsY = getIntent().getDoubleExtra("gprsY", 0);
        if(isScan){
            List<StoreDetailInfoModel.ResListBean> banners = (List<StoreDetailInfoModel.ResListBean>) getIntent().getSerializableExtra("banners");
            mImageUrl = new ArrayList<>();
            if (banners.size() > 0) {
                for (int i = 0; i < banners.size(); i++) {
                    mImageUrl.add(banners.get(i).getResUrl());
                }
            }
        }else {
            List<NearStoreListModel.ResList> banners = (List<NearStoreListModel.ResList>) getIntent().getSerializableExtra("banners");
            mImageUrl = new ArrayList<>();
            if (banners.size() > 0) {
                for (int i = 0; i < banners.size(); i++) {
                    mImageUrl.add(banners.get(i).getResUrl());
                }
            }
        }
        tvTitleCompanyName.setText(storeName);
        tvStoreDescribe.setText(description);
        String srtPhone = "电话: <font color='#09c0c7'>" + serviceNumber + "</font>";
        String srtAddress = "地址: <font color='#09c0c7'>" + storeLocation + "</font>";
        tvStoreNumber.setText(Html.fromHtml(srtPhone));
        tvStoreAdress.setText(Html.fromHtml(srtAddress));
        mEndPoint = new LatLonPoint(gprsY, gprsX);//终点

        imgTop.setImageResources(mImageUrl, mImageUrlweb, mAdCycleViewListener);
        setTitleLayout(lineHeadView);
        lineHeadView.setFocusable(true);
        lineHeadView.setFocusableInTouchMode(true);
        lineHeadView.requestFocus();
        lineHeadView.getBackground().setAlpha(0);//开始是透明的
        myScrollView.setScrollViewLine(this);
        storeId = getIntent().getIntExtra("storeId", 0);
        myLoadView = new MyLoadView(this, "正在加载");
        //获取地图对象
        amap = mapView.getMap();
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(this);


    }

    private ImageCycleView.ImageCycleViewListener mAdCycleViewListener = new ImageCycleView.ImageCycleViewListener() {
        @Override
        public void onImageClick(int position, View imageView) {
            // TODO 单击图片处理事件

        }

        @Override
        public void displayImage(String imageURL, final ImageView imageView) {

            GlideUtils.loadImage(NoBindStoreDetailActivity.this, imageURL, imageView, new GlideUtils.ImageLoadListener<String, GlideDrawable>() {
                @Override
                public void onLoadingComplete(String uri, ImageView view, GlideDrawable resource) {

                }

                @Override
                public void onLoadingError(String source, Exception e) {

                }
            }, R.mipmap.default_icon, R.mipmap.default_icon);


        }
    };
    //适配6.0的动态权限管理
//    打开位置权限

    public void onClickLocation() {
        Acp.getInstance(NoBindStoreDetailActivity.this).request(new AcpOptions.Builder().setPermissions(Manifest.permission.ACCESS_FINE_LOCATION).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {

                    }

                    @Override
                    public void onDenied(List<String> permissions) {

                        PhoneUtils.ShowToastMessage(NoBindStoreDetailActivity.this, permissions.toString() + "权限拒绝");
                    }
                });

    }

    //计算驾车路线
    private void calculateDriveRoute(LatLonPoint mStartPoint, LatLonPoint mEndPoint) {
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(mStartPoint, mEndPoint);
        // 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DrivingDefault, null, null, "");
        mRouteSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        myScrollView.requestDisallowInterceptTouchEvent(true);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int i) {
        if (i == 1000) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    final DrivePath drivePath = result.getPaths().get(0);
                    DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
                            this, amap, drivePath,
                            result.getStartPos(),
                            result.getTargetPos());
                    drivingRouteOverlay.removeFromMap();
                    drivingRouteOverlay.addToMap();
                    drivingRouteOverlay.zoomToSpan();
                    drivingRouteOverlay.setNodeIconVisibility(false);

                }
            }
        }
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }

    //  定位回调监听事件
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    amapLocation.getLatitude();//获取纬度
                    amapLocation.getLongitude();//获取经度
                    amapLocation.getAccuracy();//获取精度信息
                    // 如果不设置标志位，此时再拖动地图时，它会不断将地图移动到当前的位置
                    if (isFirstLoc) {
                        //设置缩放级别
                        amap.moveCamera(CameraUpdateFactory.zoomTo(16));
                        //将地图移动到定位点
                        amap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude())));
                        //添加图钉
//                        amap.addMarker(getMarkerOptions(amapLocation));
                        isFirstLoc = false;
                        mStartPoint = new LatLonPoint(amapLocation.getLatitude(), amapLocation.getLongitude());//起点，

                        calculateDriveRoute(mStartPoint, mEndPoint);
                    }

                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("qwe", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    //定位初始化控件配置
    private void initLoc() {
        locationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        locationClient.setLocationListener(mAMapLocationListener);
        //初始化定位参数
        locationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        locationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        locationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        locationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        locationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        locationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        locationClient.setLocationOption(locationOption);
        //启动定位
        locationClient.startLocation();

    }


    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.stopLocation();
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
        mapView.onDestroy();

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }


    public void onClickCallPhone() {
        Acp.getInstance(this).request(new AcpOptions.Builder().setPermissions(Manifest.permission.CALL_PHONE).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        ExitLoginDialog(serviceNumber, "", "呼叫", "取消");
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        PhoneUtils.ShowToastMessage(NoBindStoreDetailActivity.this, permissions.toString() + "权限拒绝");

                    }
                });

    }

    private void ExitLoginDialog(final String title, String msg, String sure, String cancle) {
        new UniversalDialog(NoBindStoreDetailActivity.this).builder().setTitle(title)
//                .setMsg(msg)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_CALL);
                        intent.setData(Uri.parse("tel:" + title));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);

                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }


    private void BindDialog(String title, String sure, String cancle) {
        new UniversalDialog(NoBindStoreDetailActivity.this).builder().setTitle(title)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BindStore();
                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }


    private void BindStore() {
        ownerInfoModel = UserHelper.getInstance().getOwnerInfoModel(NoBindStoreDetailActivity.this);
        BindStoreApi bindStoreApi = new BindStoreApi(new HttpOnNextListener<StoreDataModel>() {
            @Override
            public void onNext(StoreDataModel model) {
                Gson gson = new GsonBuilder().create();
                String data = gson.toJson(model);
                UserHelper.getInstance().saveChainStores(NoBindStoreDetailActivity.this, data);
                MessageHelper.getInstance().reset();
                EMClient.getInstance().login(UserHelper.getInstance().getUserInfoModel(NoBindStoreDetailActivity.this).getImKey(), UserHelper.getInstance().getUserInfoModel(NoBindStoreDetailActivity.this).getImPasswd(), new EMCallBack() {//回调
                    @Override
                    public void onSuccess() {
                        MessageHelper.getInstance().getUserProfileManager().setCurrentUser(UserHelper.getInstance().getUserInfoModel(NoBindStoreDetailActivity.this.getApplicationContext()).getNickName(),
                                UserHelper.getInstance().getUserInfoModel(NoBindStoreDetailActivity.this.getApplicationContext()).getUserLogo());

                        EMClient.getInstance().groupManager().loadAllGroups();
                        EMClient.getInstance().chatManager().loadAllConversations();
                        MyLog.d("King", "登录聊天服务器成功！");
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }

                    @Override
                    public void onError(int code, String message) {
                        MyLog.d("King", "登录聊天服务器失败！" + code + "|" + message);
                    }
                });
                for (int i = 0; i <model.getChainStores().size(); i++) {
                    if(model.getChainStores().get(i).getStoreId()==storeId){
                        String storeName = model.getChainStores().get(i).getStoreName();
                        ownerInfoModel.setStoreName(storeName);
                        break;
                    }
                }
                ownerInfoModel.setStoreId(storeId);
                ownerInfoModel.setBindStoreId(storeId);
                SharedPreferencesUtils.setParam(NoBindStoreDetailActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, storeId);
                UserHelper.getInstance().setOwnerInfoModel(NoBindStoreDetailActivity.this, ownerInfoModel);
                UserHelper.getInstance().setSelectStoreId(NoBindStoreDetailActivity.this, storeId);
                PhoneUtils.ShowToastMessage(NoBindStoreDetailActivity.this, "绑定成功");
                setResult(RESULT_OK);
                finish();
            }
        }, this);

        bindStoreApi.setSession(UserHelper.getInstance().getSessionInfoModel(NoBindStoreDetailActivity.this).getSession());
        bindStoreApi.setStoreId(storeId + "");
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(bindStoreApi);


    }


    protected void setTitleLayout(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int statusBarHeight = getStatusBarHeight(NoBindStoreDetailActivity.this.getBaseContext());
            view.setPadding(0, statusBarHeight, 0, 0);

        }
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Override
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
        if (oldt < 10) {
            lineHeadView.getBackground().setAlpha(0);
        } else if (oldt < 50 && oldt > 10) {
            lineHeadView.getBackground().setAlpha(oldt / 8);
        } else if (oldt < 100 && oldt > 50) {
            lineHeadView.getBackground().setAlpha(oldt / 6);

        } else if (oldt < 150 && oldt > 100) {
            lineHeadView.getBackground().setAlpha(oldt / 4);
        } else if (oldt < 200 && oldt > 150) {
            lineHeadView.getBackground().setAlpha(oldt / 2);
        } else if (oldt >= 200) {
            lineHeadView.getBackground().setAlpha(255);
        }
    }

    //    导航去店
    public static void navigation(Context ctx, double Y, double X) {
        try {
            if (AMapUtil.isInstallByRead("com.autonavi.minimap")) {
                AMapUtil.goToNaviActivity(ctx, ctx.getString(R.string.app_name), null, Y, X, "0", "2");
            } else {
                Intent ti = new Intent(ctx, GPSNaviActivity.class);
                ti.putExtra("mEndPoint", Y + "/" + X);
                ctx.startActivity(ti);
            }
        } catch (Exception e) {
            PhoneUtils.ShowToastMessage(ctx, "坐标设置错误");
        }
    }

    //适配6.0的动态权限管理//打开位置权限
    public static void locationNavigation(final Context ctx, final double Y, final double X) {
        Acp.getInstance(ctx).request(new AcpOptions.Builder().setPermissions(Manifest.permission.ACCESS_FINE_LOCATION).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        try {
                            if (AMapUtil.isInstallByRead("com.autonavi.minimap")) {
                                AMapUtil.goToNaviActivity(ctx, ctx.getString(R.string.app_name), null, Y, X, "0", "2");
                            } else {
                                Intent ti = new Intent(ctx, GPSNaviActivity.class);
                                ti.putExtra("mEndPoint", Y + "/" + X);
                                ctx.startActivity(ti);

                            }
                        } catch (Exception e) {
                            PhoneUtils.ShowToastMessage(ctx, "坐标设置错误");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        PhoneUtils.ShowToastMessage(ctx, permissions.toString() + "权限拒绝");
                    }
                });
    }

    @OnClick({R.id.img_navigation, R.id.img_store_number, R.id.floatinImgBtn, R.id.img_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_navigation:
                try {
                    if ((Build.VERSION.SDK_INT >= 23)) {
                        locationNavigation(NoBindStoreDetailActivity.this, gprsY, gprsX);
                    } else {
                        navigation(NoBindStoreDetailActivity.this, gprsY, gprsX);
                    }

                } catch (Exception e) {
                    PhoneUtils.ShowToastMessage(NoBindStoreDetailActivity.this, "门店坐标未设置");
                }
                break;
            case R.id.img_store_number:
                if ((Build.VERSION.SDK_INT >= 23)) {
                    onClickCallPhone();
                } else {
                    ExitLoginDialog(serviceNumber, "", "呼叫", "取消");
                }
                break;
            case R.id.floatinImgBtn:
                SharedPreferencesUtils.setParam(NoBindStoreDetailActivity.this, Constants.SHARED_PREFERENCES_KEY_IS_STORE_BIND_DIALOG, storeId);
                MyLog.e("yang","storeId==="+storeId);
                SharedPreferencesUtils.setParam(NoBindStoreDetailActivity.this, Constants.SHARED_PREFERENCES_KEY_IS_STORE_BIND, true);
                if(checkLoginState()){
                    BindDialog(getString(R.string.bind_store_title), getString(R.string.sure_bind), getString(R.string.cancle_bind));
                }
                break;
            case R.id.img_back:
                finish();
                break;
        }
    }
}
